<html>
<body onload="webGLStart();">

<div id="leftCol">
	  </br><input type="button" value="Triangulo" onClick="figura='TRIANGULO'">
	  </br><input type="button" value="Cuadrado"  onClick="figura='CUADRADO'">
	  </br><input type="button" value="Linea"     onClick="figura='LINEA'">
	  </br></br>
	  FONDOS EN:
	  </br><input type="button" value="Azul"     onClick="gl.clearColor(0.3, 0.15, 0.6, 1.0); drawScene();">
	  </br><input type="button" value="Blanco"     onClick="gl.clearColor(1.0, 1.0, 1.0, 1.0); drawScene();">
	  </br><input type="button" value="Negro"     onClick="gl.clearColor(0, 0, 0, 1.0); drawScene();">

  </div>

  <div id="canvas">
  	   <canvas id="FiuniPaint" style="border: none;" width="500" height="500"></canvas>
  </div>

  <div id="rightCol">
	  	<form name="form">
	  	</br>
	  	Selecciona Elemento
<select name="dropdownbox" size=1>
<option>Selecciona elemento</option>
</select>
</br>

		Angulo<input size="6" maxlength="4" id="iRotar">
		<input type="button" value="Rotar"     onClick="rotar();">

		</br>Trasladar a :
		X:<input size="3" maxlength="2" id="iX">
		Y:<input size="3" maxlength="2" id="iY">
		<input type="button" value="Trasladar"     onClick="trasladar();">

</form>
       <div id="pickerPanel" class="dragPanel">
            <h4 id="pickerHandle">&nbsp;</h4>
            <div id="pickerDiv">
              <img id="pickerbg" src="img/pickerbg.png" alt="">
              <div id="selector" ><img src="img/select.gif"></div>
            </div>

             <div id="hueBg">
              <div id="hueThumb"><img src="img/hline.png"></div>
            </div>

            <div id="pickervaldiv">
                <form name="pickerform" onsubmit="return pickerUpdate()">
                <br />
                R <input name="pickerrval" id="pickerrval" type="text" value="0" size="3" maxlength="3" />
                H <input name="pickerhval" id="pickerhval" type="text" value="0" size="3" maxlength="3" />
                <br />
                G <input name="pickergval" id="pickergval" type="text" value="0" size="3" maxlength="3" />
                S <input name="pickergsal" id="pickersval" type="text" value="0" size="3" maxlength="3" />
                <br />
                B <input name="pickerbval" id="pickerbval" type="text" value="0" size="3" maxlength="3" />
                V <input name="pickervval" id="pickervval" type="text" value="0" size="3" maxlength="3" />
                <br />
                <br />
                # <input name="pickerhexval" id="pickerhexval" type="text" value="0" size="6" maxlength="6" />
                <br />

                </form>
            </div>

            <div id="pickerSwatch">&nbsp;</div>
        </div>

    </div>

</body>

<head>

<title>FiuniPaint v0.1</title>

<link rel="stylesheet" type="text/css" href="css/estilo.css">
<link rel="stylesheet" type="text/css" href="css/screen.css">


<script type="text/javascript" src="js/ddcolorposter.js"></script>
<script type="text/javascript" src="js/YAHOO.js" ></script>
<script type="text/javascript2" src="js/log.js" ></script>
<script type="text/javascript" src="js/color.js" ></script>
<script type="text/javascript" src="js/event.js" ></script>
<script type="text/javascript" src="js/dom.js" ></script>
<script type="text/javascript" src="js/animation.js" ></script>
<script type="text/javascript" src="js/dragdrop.js" ></script>
<script type="text/javascript" src="js/slider.js" ></script>


<script type="text/javascript" language="javascript" src="js/yuiColorpicker.js"></script>
<script type="text/javascript" src="sylvester.js"></script>
<script type="text/javascript" src="glUtils.js"></script>
<script type="text/javascript" src="lista.js"></script>
<script type="text/javascript" src="dibujos.js"></script>

<script type="text/javascript">

var lista;
var mouseDown=false;
  function webGLStart() {
	lista = CrearLista();
    var canvas = document.getElementById("FiuniPaint");

    initGL(canvas);

    initShaders();
    drawScene();

   // initBuffers();  <!-- Aqui cargamos el tipo de objetos que vamos a dibujar -->

    <!-- Funciones para inicializar la escena -->

    gl.clearColor(0.0, 0.0, 0.0, 1.0);

    gl.clearDepth(1.0);

    gl.enable(gl.DEPTH_TEST);

    gl.depthFunc(gl.LEQUAL);

    //setInterval(drawScene, 5);


    canvas.addEventListener('mousedown', handleMouseDown, false);
    canvas.addEventListener('mousemove', handleMouseMove, false);
    canvas.addEventListener('mouseup',   handleMouseUp, false);

  }




 var x1= 0;
 var y1= 0;
 var x2= 0;
 var y2= 0;
 var figura="LINEA";
 var r=0;
 var g=0;
 var b=0;
 var o=0;

function posicion (x1, y1, x2, y2)
{
        this.x1=x1;
        this.y1=y1;
        this.x2=x2;
        this.y2=y2;
}

   function handleMouseDown(event) {
        mouseDown = true;
       // x1 = event.clientX;
        //y1 = event.clientY;

      var w = gl.viewportWidth ;

      var h =  gl.viewportHeight;
      // calculate x,y clip space coordinates
     //alert(event.pageX+" "+event.clientX+" "+event.layerX );
      x1 = (event.layerX - (w)/2) / ((w)/2) ;
      	  //multiplico por 5 porque se que es un valor apro de la el tam aprox max de "X" en el plano ortogonal
      x1 = x1*5;

      y1 = (event.layerY - (h)/2)/((h)/2) ;
      	  //multiplico por 5 porque se que es un valor apro de la el tam aprox max de "Y" en el plano ortogonal
      y1 = -y1*5;

	  //para visualizar en la pantalla los valores de posicion del mouse

    }


    function handleMouseUp(event) {
      mouseDown = false;
 		initBuffers();
	  drawScene();
    }


    function handleMouseMove(event) {
        if (!mouseDown) {
            return;
        }
           var w = gl.viewportWidth ;

      var h = gl.viewportHeight ;



      x2 = (event.layerX  - (w)/2) / ((w)/2) ;
	  //multiplico por 5 porque se que es un valor apro de la el tam aprox max de "X" en el plano ortogonal
      x2 = x2*5;

      y2 = (event.layerY  - (h)/2)/((h)/2) ;;
	  //multiplico por 5 porque se que es un valor apro de la el tam aprox max de "Y" en el plano ortogonal
      y2 = -y2*5;

    }

    var gl;
    function initGL(canvas) {
<!--Obtenemos el contexto y los tamaÃ±os definidos para el canvas -->
        try {
            gl = canvas.getContext("experimental-webgl");
            gl.viewportWidth = canvas.width;
            gl.viewportHeight = canvas.height;
        } catch(e) {
        }
        <!-- Comprobamos que se ha podido inicializar correctamente -->
        if (!gl) {
        alert("Lo sentimos, no se ha podido inicializar webGL\n\nRevise la parte de configuración de nuestro tutorial");
        }
    }

var elemento =0
function initBuffers() {

r =document.getElementById("pickerrval").value;

g =document.getElementById("pickergval").value;

b =document.getElementById("pickerbval").value;

var dib = new dibujo(figura,x1,y1,x2,y2,(r/255),(g/255),(b/255),1.0);

ListaGuardar(lista, dib);

addDropBox((lista.index)-1);

}

  function getShader(gl, id) {
    var shaderScript = document.getElementById(id);
    if (!shaderScript) {
      return null;
    }

    var str = "";
    var k = shaderScript.firstChild;
    while (k) {
      if (k.nodeType == 3) {
        str += k.textContent;
      }
      k = k.nextSibling;
    }

    var shader;
    if (shaderScript.type == "x-shader/x-fragment") {
      shader = gl.createShader(gl.FRAGMENT_SHADER);
    } else if (shaderScript.type == "x-shader/x-vertex") {
      shader = gl.createShader(gl.VERTEX_SHADER);
    } else {
      return null;
    }

    gl.shaderSource(shader, str);
    gl.compileShader(shader);

    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
      alert(gl.getShaderInfoLog(shader));
      return null;
    }

    return shader;
  }


  var mvMatrix;
  function loadIdentity() {
    mvMatrix = Matrix.I(4);
  }


  function multMatrix(m) {
    mvMatrix = mvMatrix.x(m);
  }


  function mvTranslate(v) {
    var m = Matrix.Translation($V([v[0], v[1], v[2]])).ensure4x4();
    multMatrix(m);
  }
  function mvRotate(ang, v) {
    var arad = ang * Math.PI / 180.0;
    var m = Matrix.Rotation(arad, $V([v[0], v[1], v[2]])).ensure4x4();
    multMatrix(m);
  }

  function rotar(){
  	if(!isNaN(document.getElementById("iRotar").value)){

  		var n= document.form.dropdownbox.options[document.form.dropdownbox.selectedIndex].value;

  	lista[n].rotar=document.getElementById("iRotar").value;
  	drawScene();
  	}
  	else {
  	alert("INGRESE UN NUMERO VALIDO");
  	document.getElementById("iRotar").value="";
  	}
  }
  function trasladar(){

  	if(!isNaN(document.getElementById("iX").value && !isNaN(document.getElementById("iY").value))){
  		var n= document.form.dropdownbox.options[document.form.dropdownbox.selectedIndex].value;
  		var iX=document.getElementById("iX").value;
  		var iY=document.getElementById("iY").value;
  		if(iX<10 && iX> -10)
  			lista[n].toX=iX;
  		else
  			 alert("ingrese un numero entre -10 y 10");
	    if(iY<10 && iY> -10)
  			lista[n].toY=iY;
	 	else
  		 	alert("ingrese un numero entre -10 y 10");
  	drawScene();
  	}
  	else {
  	alert("INGRESE UN NUMERO VALIDO");
  	document.getElementById("iX").value="";
  	document.getElementById("iY").value="";
  	}

  }

 var mvMatrixStack = [];
  function mvPushMatrix(m) {
    if (m) {
      mvMatrixStack.push(m.dup());
      mvMatrix = m.dup();
    } else {
      mvMatrixStack.push(mvMatrix.dup());
    }
  }
  function mvPopMatrix() {
    if (mvMatrixStack.length == 0) {
      throw "Invalid popMatrix!";
    }
    mvMatrix = mvMatrixStack.pop();
    return mvMatrix;
  }

  var pMatrix;
  function perspective(fovy, aspect, znear, zfar) {
    pMatrix = makePerspective(fovy, aspect, znear, zfar);
  }


  function setMatrixUniforms() {
    gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, new Float32Array(pMatrix.flatten()));
    gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, new Float32Array(mvMatrix.flatten()));
  }


  function drawScene() {



    <!-- Definimos una vista, con su tamaÃ±o, y la "limpiamos" -->
    gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);


    <!-- Definimos una perspectiva (para que los objetos tengan profunidad) y decidimos -->
    <!-- hasta que profundidad max y minima queremos representar -->
    perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0);




    var i;
for(i=0; i<lista.length; i++){
    loadIdentity();

    <!-- situamos el "puntero" en un lugar del espacio-->

    mvTranslate([0.0, 0.0, -12,5]);

	if(lista[i].rotar!=0 && lista[i].rotar!=null){
		mvTranslate([1.0, 0.0, -12,5]);
		mvPushMatrix();
		mvRotate(lista[i].rotar,[0,0,1] );
	}

	if(lista[i].toX<10 && lista[i].toX> -10)
	 if(lista[i].toY<10 && lista[i].toY> -10)
	    mvTranslate([lista[i].toX, lista[i].toY, -12,5]);

	//carga	mos los buffer de los vertices
    gl.bindBuffer(gl.ARRAY_BUFFER, lista[i].vertexbuffer);
    gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, lista[i].vertexItemSize, gl.FLOAT, false, 0, 0);

   //Cargamos los buffer del color
    gl.bindBuffer(gl.ARRAY_BUFFER, lista[i].colorBuffer);
    gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, lista[i].colorItemSize, gl.FLOAT, false, 0, 0);

    setMatrixUniforms();
    //dibujamos los que se encuentre el la lista segun el tipo y la cantidad de vertices a leer
    gl.drawArrays(lista[i].glTipo, 0, lista[i].vertexNumItem);
	if(lista[i].rotar!=0 && lista[i].rotar!=null){
		mvPopMatrix();

	}
   }
  }



    <!-- Funcion encargada de inicializar los shaders -->
    var shaderProgram;
    function initShaders() {
        var fragmentShader = getShader(gl, "shader-fs");
        var vertexShader = getShader(gl, "shader-vs");

        shaderProgram = gl.createProgram();
        gl.attachShader(shaderProgram, vertexShader);
        gl.attachShader(shaderProgram, fragmentShader);
        gl.linkProgram(shaderProgram);

        if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
            alert("Could not initialise shaders");
        }

        gl.useProgram(shaderProgram);

        shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram,"aVertexPosition");
        gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);

		shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor");
        gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute);

        shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix");
        shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");
    }


function addDropBox(i) {

document.form.dropdownbox[i] = new Option("elem " + i , i);

}



</script>


<script id="shader-fs" type="x-shader/x-fragment">

  #ifdef GL_ES

  precision highp float;

  #endif

  varying vec4 vColor;

  void main(void) {

    gl_FragColor = vColor;

  }

</script>



<script id="shader-vs" type="x-shader/x-vertex">

  attribute vec3 aVertexPosition;
  attribute vec4 aVertexColor;

  uniform mat4 uMVMatrix;
  uniform mat4 uPMatrix;

  varying vec4 vColor;

  void main(void) {

    gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
	vColor = aVertexColor;
  }
</script>

</head>
</html>